<script>
import dayjs from 'dayjs';
import { ElMessageBox } from 'element-plus';

export default {
  name: "student add",
  data() {
    return {
      student: {
        name: '',
        gender: '',
        birthdate: '',
        hometown: ''
      }
    }
  },
  methods: {
    open(title,message) {
      ElMessageBox.alert(message, title, {
        confirmButtonText: '确定'
      });
    },
    add() {
      const s = this.student;
      const dateOfBirth = dayjs(s.birthdate).format('YYYY-MM-DD');
      // 保存数据
      const p = fetch('/api/student', {
        method: 'POST',
        headers: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        body: `name=${s.name}&gender=${s.gender}&hometown=${s.hometown}&birthdate=${dateOfBirth}`
      });
      p.then( resp => resp.json() )
       .then( data => {
        console.log( data );
        if( data.success ) {
          // 编程式导航
          this.$router.push('/student/list');
          return;
        }
        this.open('保存失败', data.message );
      })
      .catch( reason => {
        console.error(reason);
        this.open('保存失败', reason.message );
      });
    }
  },
  unmounted() {
    console.log('卸载StudentAdd');
  }
};
</script>

<template>
  <div class="student-add">
    <h3>添加学生</h3>
    <el-form :model="student" label-width="120px">
        <el-form-item label="姓名">
            <el-input v-model="student.name"></el-input>
        </el-form-item>
        <el-form-item label="性别">
            <el-radio-group v-model="student.gender">
                <el-radio label="male" size="large">靓仔</el-radio>
                <el-radio label="female" size="large">靓妹</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
            <el-date-picker v-model="student.birthdate" type="date" :editable="false" />
        </el-form-item>
        <el-form-item label="籍贯">
            <el-input v-model="student.hometown"></el-input>
        </el-form-item>
        <el-form-item label="">
            <el-button type="primary" @click="add">添加</el-button>
        </el-form-item>
    </el-form>
  </div>
</template>

<style>
</style>